package com.cx.controller;

import com.cx.dto.PageDto;
import com.cx.pojo.LogMessage;
import com.cx.pojo.User;
import com.cx.service.impl.Service;
import com.cx.util.InsertLog;
import com.cx.vo.*;
import com.cx.dto.RegistInfo;
import com.cx.service.*;
import com.cx.util.SendMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @Description GroupOneproject-IntelliJ IDEA
 * @Author Pyc
 * @Date 2020/5/4 14:30
 * @Version 1.0
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    LoginService loginService;

    @Autowired
    RegistService registService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    MemberService memberService;

    @Autowired
    EmailService emailService;

    @Autowired
    PasswordService passwordService;

    @Autowired
    LogMessageService logMessageService;

    @Autowired
    InsertLog insertLog;

    @Autowired
    Service service;

    @RequestMapping("/login")
    @ResponseBody
    public String login(HttpServletRequest req, String userName, String password){


        System.out.println(userName);
        System.out.println(password);
        if (userName==null||password==null){
            System.out.println("spcae");
            return "space";
        }
        User user = loginService.findUser(userName);
        service.sendUserInfo(user);
        System.out.println(user);
        if (user==null){
            System.out.println("user");
            return "ufail";
        }
        if (!user.getUserPassword().equals(password)){
            System.out.println("pasw");
            return "pfail";
        }
        HttpSession session = req.getSession();
        session.setAttribute("user",user);
        System.out.println("sc");
        return "success";
    }

    @RequestMapping("/loginsuccess")
    public String loginsuccess(HttpServletRequest req){

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        if (user==null){
            System.out.println("weidinglu");
            return "login";
        }else {
            String uname = user.getUserName();
            String ip = req.getRemoteAddr();
            String message = uname + ",您的账户在"+ip+"登录,若此非您的常用ip地址，请及时更改密码。";
            insertLog.insert(user.getId(),"Security",message);
            return "redirect:/user/getuserinfo";
        }

    }

    @RequestMapping("/getuserinfo")
    public String userInfo(HttpServletRequest req ,Model model){

        HttpSession session = req.getSession();

        User user = (User) session.getAttribute("user");

        model.addAttribute("user",user);
        System.out.println("获取用户信息中。。");
        return "userinfo";
    }

    @RequestMapping("/regist")
    @ResponseBody
    public String regist(RegistInfo registInfo){

        User user = new User();
        user.setUserName(registInfo.getUserName());
        user.setUserPassword(registInfo.getPassword());
        user.setUserNum(registInfo.getUserNum());

        int result;
        if (registInfo!=null){
            result = registService.registUser(user);

            if (result > 0){
                System.out.println("ok");
                return "success";
            }else {
                System.out.println("fail");
                return "fail";
            }
        }else {
            return "fail";
        }

    }

    @RequestMapping("/checkname")
    @ResponseBody
    public String checkName(String userName){

        User user = registService.checkUser(userName);
        if (user==null){
            System.out.println("ok");
            return "ok";
        }else
            return "exist";
    }

//    得到基本信息
    @RequestMapping("/getbaseinfo")
    public String getInfo(HttpServletRequest httpServletRequest,Model model){

        HttpSession httpSession = httpServletRequest.getSession();

        User sessionUser = (User) httpSession.getAttribute("user");
        if (sessionUser==null){
            return "jump";
        }

        int id = sessionUser.getId();
        User user = userInfoService.getUserBaseInfo(id);

        if (user==null){
            return "jump";
        }else{
            model.addAttribute("info",user);
            return "userinfo_baseinfo";
        }

    }
//保存基本信息
    @RequestMapping("/savebaseinfo")
    @ResponseBody
    public String savebaseinfo(HttpSession session,UserInfoBase userInfoBase){

        User user = new User();
        User sessionuser = (User) session.getAttribute("user");
        System.out.println(sessionuser);
        if (sessionuser==null){
            return "unlogin";
        }
        int id = sessionuser.getId();
        user.setId(id);
        String userNum = userInfoBase.getUserNum();
        if (userNum==null){
            userNum = sessionuser.getUserNum();
        }
        user.setUserNum(userNum);
        String userEmail = userInfoBase.getUserEmail();
        if (userEmail==null){
            userEmail = sessionuser.getUserEmail();
        }
        user.setUserEmail(userEmail);
        String userPicture;
        if (userInfoBase.getUserPicture()!=null){

            String fileName = userInfoBase.getUserPicture().getOriginalFilename();
            System.out.println(fileName);
            fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
            System.out.println(fileName);

            File dest = new File("C://Users//赵辰君//IdeaProjects//Hotel//User//src//main//webapp//WEB-INF//img/"+fileName);
            try {
                userInfoBase.getUserPicture().transferTo(dest);
            } catch (Exception e ) {
                e.printStackTrace();
            }
            userPicture = fileName;


        }else {
            userPicture = sessionuser.getUserPicture();
        }
        user.setUserPicture(userPicture);
        System.out.println(user);


        int result = userInfoService.saveUserBaseInfo(user);
        if (result>0){
            if (sessionuser.getUserPicture()==null){
                sessionuser.setUserPicture(user.getUserPicture());
            } else if (!sessionuser.getUserPicture().equals(user.getUserPicture())){
                File oldfile = new File("C://Users//赵辰君//IdeaProjects//Hotel//User//src//main//webapp//WEB-INF//img/"+sessionuser.getUserPicture());
                boolean deleteResult = oldfile.delete();
                sessionuser.setUserPicture(user.getUserPicture());
                if (deleteResult){
                    System.out.println("旧文件已删除");
                }
            }
            String uname = sessionuser.getUserName();
            String message = uname + ",您刚刚成功修改个人资料,若此非您的操作，请及时更改密码。";
            insertLog.insert(sessionuser.getId(),"Security",message);


            System.out.println("返回图片名称"+sessionuser.getUserPicture());
            return sessionuser.getUserPicture();
        }else{
            if (sessionuser.getUserPicture()!=null&&!sessionuser.getUserPicture().equals(user.getUserPicture())){
                File dest = new File("C://Users//赵辰君//IdeaProjects//Hotel//User//src//main//webapp//WEB-INF//img/"+user.getUserPicture());
                //C:\Users\赵辰君\IdeaProjects\Hotel\User\src\main\webapp\WEB-INF\img
                boolean deleteResult = dest.delete();
                if (deleteResult){
                    System.out.println("新文件未添加");
                }
            }
            return "fail";
        }



    }
    //获取会员列表和会员信息
    @RequestMapping("/getmemberinfo")
    public String getMemberInfo(HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        System.out.println(user);
        if (user==null){
            return "jump";
        }
        UserMemberView userMemberView = new UserMemberView(user.getMemberLv(),null,user.getReward(),0);

        System.out.println(userMemberView);

        userMemberView = memberService.getMemberBy(userMemberView);

        System.out.println(userMemberView);

        List<MemberView> memberViewList = memberService.getAllMemberType();

        model.addAttribute("xx", userMemberView);

        model.addAttribute("xy", memberViewList);

        return "userinfo_memberlevel";

    }

//    //获取
//    @RequestMapping("/getmembereinfo")
//    public String getMemberInfo(HttpSession session,Model model){
//
//        int id = ((User) session.getAttribute("user")).getId();
//        User user = userInfoService.getUserBaseInfo(id);
//
//        if (user==null){
//            return "login";
//        }else{
//            model.addAttribute("info",user);
//            return "userinfo_baseinfo";
//        }
//
//    }

    @RequestMapping("/email")
    @ResponseBody
    public String email(HttpSession session,String email) {

        System.out.println("email:" + email);
        User user = emailService.getUserByEmail(email);
        if (user == null) {
            return "fail";
        }else {
            System.out.println(user);
            if(session.getAttribute("emailuser")!=null){
                return "fail";
            }
            session.setAttribute("emailuser",user);
//            生成验证码
            String strFont = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
            char[] fonts = strFont.toCharArray();
            StringBuffer codeBuffer = new StringBuffer();
            Random random = new Random();
            for (int i = 0;i<5;i++){
                int order = random.nextInt(59);
                codeBuffer.append(fonts[order]);
            }
            System.out.println(codeBuffer);
            String code = codeBuffer.toString();
            SendMail.send(email,code);
            session.setAttribute("code",code);
            session.setMaxInactiveInterval(60);
            return "success";

        }
    }

    @RequestMapping("/emaillogin")
    @ResponseBody
    public String emailLogin(HttpSession session, EmailCode emailCode) {

        System.out.println(emailCode);

        String code = (String) session.getAttribute("code");
        if (emailCode.getCode().toLowerCase().equals(code.toLowerCase())){
            session.setMaxInactiveInterval(3600);
            session.removeAttribute("code");
            User user = (User)session.getAttribute("emailuser");
            session.setAttribute("user", user);
            System.out.println("验证码校验正确");
            System.out.println(user.getUserName()+"通过邮箱登录！");

            return "success";
        }else {
            return "fail";
        }
    }

    @RequestMapping("/managepassword")
    public String managePassword(){

        return "userinfo_changepwd";
    }

    @RequestMapping("/changepassword")
    @ResponseBody
    public String changePassword(HttpSession session,Password password) {

        User user = (User) session.getAttribute("user");
        if (user == null){
            return "loginfail";
        }
        if (user.getUserPassword().equals(password.getOriginPassword())){


            User updateUser = new User();
            updateUser.setId(user.getId());
            updateUser.setUserPassword(password.getNewPassword());

            int result = passwordService.changePassword(updateUser);
            if (result>0){
                System.out.println("xiugaichenggong");
                String uname = user.getUserName();
                String message = uname + ",您成功修改密码，若该操作非本人，可以通过绑定邮箱找回密码。";
                insertLog.insert(user.getId(),"Security",message);
                session.removeAttribute("user");
                return "success";
            }else
                return "fail";
        }else {
            return "orifail";
        }
    }

    @RequestMapping("/emailpwd")
    public String emailPwd(HttpSession session,Model model){

        User user = (User) session.getAttribute("user");
        model.addAttribute("user",user);
        return "email_changepassword";
    }

    @RequestMapping("/getbackpassword")
    @ResponseBody
    public String getBackPassword(HttpSession session,String newpassword) {

        User user = (User) session.getAttribute("user");
        if (user == null){
            return "loginfail";
        }
        User userExample = new User();
        userExample.setId(user.getId());
        System.out.println(newpassword);
        if (newpassword!=null){

            userExample.setUserPassword(newpassword);

            int result = passwordService.changePassword(userExample);
            if (result>0){
                System.out.println("xiugaichenggong");
                String uname = user.getUserName();
                String message = uname + ",您成功通过邮箱找回密码。";
                insertLog.insert(user.getId(),"Security",message);
                session.removeAttribute("user");

                return "success";
            }else
                return "fail";
        }else {
            return "fail";
        }
    }

    @RequestMapping("/getlogmessage")
    public String getLogMessage(HttpSession session, Model model, PageDto pageDto){

        User user = (User) session.getAttribute("user");
        if (user==null){
            return "login";
        }
        System.out.println(pageDto);
        List<LogMessage> logMessages = logMessageService.selectByUid(user.getId(),pageDto);

        System.out.println(pageDto);

        logMessages.forEach(System.out::println);


        model.addAttribute("logs",logMessages);
        model.addAttribute("page", pageDto);

        return "userinfo_log";
    }

    @RequestMapping("/afterread")
    @ResponseBody
    public LogMessage afterRead(int id){


        int result = logMessageService.afterRead(id);
        LogMessage logMessage = logMessageService.selectByid(id);

        return logMessage;
    }

    @RequestMapping("/deletelog")
    @ResponseBody
    public String deleteLog(int id){

        int result = logMessageService.delMessage(id);

        return String.valueOf(result);
    }


}
